﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.DatabaseAccessor;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using YShop.Application.Contracts.Shop.Inventorys;
using YShop.Application.Contracts.Shop.Orders;
using YShop.Application.Contracts.Shop.Products;
using YShop.Core.Entites;
using YShop.Core.Managers.Caches;

namespace YShop.Application.Shop
{
    /// <summary>
    /// 销售订单
    /// </summary>
    [ApiDescriptionSettings("Shop")]
    public class OrderService:IBaseService
    {
        private readonly IRepository<Order> _repository;
        private readonly IInventoryService _inventoryService;
        private readonly IProductService _productService;
        private readonly CacheManager _cacheManager;

        public OrderService(
            IRepository<Order> repository,
            IInventoryService inventoryService,
            IProductService productService,
            CacheManager cacheManager)
        {
            _repository = repository;
            _inventoryService = inventoryService;
            _productService = productService;
            _cacheManager = cacheManager;
        }

        /// <summary>
        /// 订单提交
        /// 创建订单并锁定库存
        /// </summary>
        /// <param name="submitInputDto"></param>
        public async Task<Order> Submit(OrderSubmitInputDto submitInputDto)
        {
            var order = submitInputDto.Adapt<Order>();

            foreach(var item in order.Items)
            {
                var product = await _productService.GetAsync(item.ProductId);
                var sku = product.Details.Find(s => s.Id == item.ProductDetailId);

                item.Amount = sku.Price * item.Quantity;
            }

            // 锁定库存
            await _inventoryService.LockAsync(submitInputDto.Items.ToDictionary(k=>k.ProductDetailId,v=>v.Quantity));

            // 插入
            var result = await _repository.InsertAsync(order);

            return result.Entity;
        }

       
        public async Task<Order> Cencel(string orderId)
        {
            var order = await _repository.FirstOrDefaultAsync(s => s.Id == orderId,true);


            return order;
        }
    }
}
